<template>
  <div class="performance-management">
    <div class="table-header">
      <el-input
        v-model="searchKeyword"
        placeholder="搜索员工姓名"
        style="width: 300px"
        clearable
        @clear="handleSearchClear"
        @keyup.enter="handleSearch"
      >
        <template #append>
          <el-button @click="handleSearch">
            <el-icon>
              <Search />
            </el-icon>
          </el-button>
        </template>
      </el-input>

      <!-- <el-button type="primary" @click="$emit('add-performance')">
        <el-icon>
          <Plus />
        </el-icon>
        新增绩效记录
      </el-button> -->
    </div>

    <el-table
      :data="filteredPerformances"
      style="width: 100%"
      v-loading="loading"
      stripe
    >
      <el-table-column
        type="index"
        prop="id"
        label="绩效ID"
        width="100"
        align="center"
      />
      <el-table-column
        prop="employeeName"
        label="员工姓名"
        width="120"
        align="center"
      />
      <el-table-column
        prop="period"
        label="考核周期"
        width="120"
        align="center"
      >
        <template #default="scope">
          <el-tag>{{ scope.row.period }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        prop="evaluationDate"
        label="评估日期"
        width="120"
        align="center"
      />
      <el-table-column
        prop="overallScore"
        label="综合评分"
        width="140"
        align="center"
      >
        <template #default="scope">
          <el-rate
            v-model="scope.row.overallScore"
            disabled
            show-score
            text-color="#ff9900"
            score-template="{value}"
          />
        </template>
      </el-table-column>
      <el-table-column label="能力维度评分" width="240" align="center">
        <template #default="scope">
          <div class="dimension-scores">
            <div class="score-item">
              <span class="score-label">绩效领导力:</span>
              <el-rate
                v-model="scope.row.leadershipScore"
                disabled
                show-score
                text-color="#ff9900"
                score-template="{value}"
                size="small"
              />
            </div>
            <div class="score-item">
              <span class="score-label">技术能力:</span>
              <el-rate
                v-model="scope.row.technicalScore"
                disabled
                show-score
                text-color="#ff9900"
                score-template="{value}"
                size="small"
              />
            </div>
            <div class="score-item">
              <span class="score-label">人际交往能力:</span>
              <el-rate
                v-model="scope.row.communicationScore"
                disabled
                show-score
                text-color="#ff9900"
                score-template="{value}"
                size="small"
              />
            </div>
            <div class="score-item">
              <span class="score-label">团队协作:</span>
              <el-rate
                v-model="scope.row.teamworkScore"
                disabled
                show-score
                text-color="#ff9900"
                score-template="{value}"
                size="small"
              />
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column
        prop="evaluator"
        label="评估人"
        width="120"
        align="center"
      />
      <el-table-column
        prop="achievements"
        label="主要成果"
        show-overflow-tooltip
        align="center"
      />
      <!-- <el-table-column label="操作" width="180" fixed="right" align="center">
        <template #default="scope">
          <el-button
            size="small"
            type="primary"
            link
            @click="$emit('edit-performance', scope.row)"
          >
            编辑
          </el-button>
          <el-button
            size="small"
            type="danger"
            link
            @click="$emit('delete-performance', scope.row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column> -->
    </el-table>

    <div class="pagination-container">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script>
import { ref, computed, onMounted, watch } from "vue";
import api from "@/services/api";

export default {
  name: "PerformanceManagement",
  props: {
    performances: {
      type: Array,
      default: () => [],
    },
    employees: {
      type: Array,
      default: () => [],
    },
    name: {
      type: String,
      default: () => "",
    },
  },
  emits: ["add-performance", "edit-performance", "delete-performance"],
  setup(props) {
    const searchKeyword = ref("");
    const currentPage = ref(1);
    const pageSize = ref(10);
    const loading = ref(false);
    const filteredPerformances = ref([]);

    watch(
      () => props.name,
      async (val) => {
        searchKeyword.value = val;
        await api
          .getPerformanceRecordByName(val)
          .then((response) => {
            filteredPerformances.value = response.data;
          })
          .catch((error) => {
            console.error("搜索员工/课程失败:", error);
          });
      },
      { immediate: true }
    );

    // watch(() => props.performances, async () => {
    //   try {
    //     const resPerformances = await api.getPerformances()
    //     filteredPerformances.value = resPerformances.data
    //   } catch (error) {
    //     console.error('加载绩效数据失败:', error)
    //   }
    // })

    onMounted(async () => {
      if (props.name) {
        return;
      } else {
        try {
          const res = await api.getPerformances();
          filteredPerformances.value = res.data;
        } catch (error) {
          console.error("加载绩效数据失败:", error);
        }
      }
    });

    // const filteredPerformances = computed(() => {
    //   let filtered = props.performances

    //   if (searchKeyword.value) {
    //     filtered = filtered.filter(performance =>
    //       performance.employee?.name?.includes(searchKeyword.value)
    //     )
    //   }

    //   const start = (currentPage.value - 1) * pageSize.value
    //   const end = start + pageSize.value
    //   return filtered.slice(start, end)
    // })

    const total = computed(() => {
      if (searchKeyword.value) {
        return props.performances.filter((performance) =>
          performance.employee?.name?.includes(searchKeyword.value)
        ).length;
      }
      return props.performances.length;
    });

    const handleSearch = async () => {
      currentPage.value = 1;
      if (searchKeyword.value) {
        try {
          const res = await api.getPerformanceRecordByName(searchKeyword.value);
          filteredPerformances.value = res.data;
        } catch (error) {
          console.error("搜索员工失败:", error);
        }
      }
    };

    const handleSearchClear = async () => {
      currentPage.value = 1;
      try {
        const res = await api.getPerformances();
        filteredPerformances.value = res.data;
      } catch (error) {
        console.error("加载绩效数据失败:", error);
      }
    };

    const handleSizeChange = (newSize) => {
      pageSize.value = newSize;
      currentPage.value = 1;
    };

    const handleCurrentChange = (newPage) => {
      currentPage.value = newPage;
    };

    return {
      searchKeyword,
      currentPage,
      pageSize,
      loading,
      filteredPerformances,
      total,
      handleSearch,
      handleSizeChange,
      handleCurrentChange,
      handleSearchClear,
    };
  },
};
</script>

<style scoped>
.performance-management {
  padding: 20px 0;
}

.table-header {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.dimension-scores {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.score-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.score-label {
  font-size: 12px;
  color: #909399;
  min-width: 60px;
}
</style>
